/*******************************************************************************
 * Copyright (c) 2011 LegSem.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/
package com.legsem.legstar.connector.it.jee6.ejb.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.legsem.legstar.connector.it.jee6.ejb.ClientBean;
import com.legsem.legstar.connector.it.jee6.ejb.ClientBeanException;
import com.legstar.test.coxb.lsfileae.Dfhcommarea;

/**
 * This is used to test the transactional capabilities of the connector in a
 * container-managed situation. Updates are performed by an EJB bean.
 * <p/>
 * Browser clients invoke this servlet using HTTP GET commands, with the
 * following query parameters:
 * <ul>
 * <li>oper: is the operation requested each corresponding to one of the EJB
 * methods: C for createClient, R for readClient, F for failCreateClient and D
 * for deleteClient</li>
 * <li>id: is the client id (for new clients the rest of the data is generated
 * programmatically)</li>
 * </ul>
 */
@WebServlet("/EjbClientServlet")
public class EjbClientServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @EJB
    ClientBean clientBean;

    /**
     * Dispatches the execution request depending on query parameters.
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            String oper = request.getParameter("oper");

            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title> Results from bean execution </title>");
            out.println("</head>");
            out.println("<body>");

            if (isValidRequest(id, oper, out)) {
                if (oper.equals("C")) {
                    clientBean.createClient(createDfhcommarea(id));
                    out.println("<h1>" + "Client " + id + " created" + "</h1>");
                } else if (oper.equals("R")) {
                    clientBean.readClient(readDfhcommarea(id));
                    out.println("<h1>" + "Client " + id + " read" + "</h1>");
                } else if (oper.equals("F")) {
                    clientBean.failCreateClient(createDfhcommarea(id));
                    out.println("<h1>" + "Client " + id + " updated" + "</h1>");
                } else if (oper.equals("D")) {
                    clientBean.deleteClient(readDfhcommarea(id));
                    out.println("<h1>" + "Client " + id + " deleted" + "</h1>");
                }
            }

            out.println("</body>");
            out.println("</html>");
            out.close();
        } catch (ClientBeanException e) {
            throw new ServletException(e);
        }

    }

    /**
     * Check if this is a valid request.
     * 
     * @param id a Client ID
     * @param oper an operation to perform on that client
     * @param out the HTML response
     * @return true if the requerst is fine
     */
    private boolean isValidRequest(String id, String oper, PrintWriter out) {
        if (id == null) {
            out.println("You must specify an id parameter");
            return false;
        }
        if (!id.matches("\\d{1,6}")) {
            out.println("Id must contain only digits (1 to 6)");
            return false;
        }
        if (oper == null) {
            out.println("You must specify an oper parameter (values: C for CREATE, R for READ, F for FAILURE, D for DELETE");
            return false;
        }
        if (!"CRFD".contains(oper)) {
            out.println("Invalid operation"
                    + oper
                    + ". Valid values for oper: C for CREATE, R for READ, F for FAILURE, D for DELETE");
            return false;
        }
        return true;
    }

    /**
     * Creates Client data for a new client ID.
     * 
     * @param id the new client ID
     * @return the commarea filled with test data
     */
    private Dfhcommarea createDfhcommarea(String id) {
        Dfhcommarea commarea = new Dfhcommarea();
        commarea.setComNumber(Long.valueOf(id));
        commarea.setComAmount(new BigDecimal(Long.valueOf(id) * 3.14)
                .toString());
        commarea.setComDate("12111965");
        com.legstar.test.coxb.lsfileae.ComPersonal personal = new com.legstar.test.coxb.lsfileae.ComPersonal();
        personal.setComAddress(id + " street");
        personal.setComName("P" + id);
        personal.setComPhone("0123456789");
        commarea.setComPersonal(personal);
        return commarea;

    }

    /**
     * Client data for an existing client ID.
     * 
     * @param id the new client ID
     * @return the commarea filled with test data
     */
    private Dfhcommarea readDfhcommarea(String id) {
        Dfhcommarea commarea = new Dfhcommarea();
        commarea.setComNumber(Long.valueOf(id));
        return commarea;

    }
}
